Lazy Loading

  • 1. Step

    1. Install React Router

    
                  npm install react-router-dom
                

    2. Project Structure

    
    
                src/
                  ├── App.js
                  ├── pages/
                  │   ├── Home.js
                  │   ├── About.js
                  │   └── Dashboard.js
    
                  

    3. Create Page Components

    pages/Home.js

    
                    export default function Home() {
                      return <h2>Home Page</h2>;
                    }
                    

    pages/About.js

    
                      export default function About() {
                        return <h2>About Page</h2>;
                      }
    
                      

    pages/Dashboard.js

    
                        export default function Dashboard() {
                          return <h2>Dashboard Page (Lazy Loaded)</h2>;
                        }
    
                        

    4. Setup Lazy Loading in App.js

    
                          import React, { Suspense, lazy } from 'react';
    import { BrowserRouter, Routes, Route } from 'react-router-dom';
    
    // 🔁 Lazy load components
    const Home = lazy(() => import('./pages/Home'));
    const About = lazy(() => import('./pages/About'));
    const Dashboard = lazy(() => import('./pages/Dashboard'));
    
    function App() {
      return (
        <BrowserRouter>
          <Suspense fallback={<div>Loading page...</div>}>
            <Routes>
              <Route path="/" element={<Home />} />
              <Route path="/about" element={<About />} />
              <Route path="/dashboard" element={<Dashboard />} />
            </Routes>
          </Suspense>
        </BrowserRouter>
      );
    }
    
    export default App;
    
    

    React.lazy() dynamically loads the component only when the route is accessed

    Suspense fallback={...} shows a loading placeholder until the component is loaded